use crate::{
    AppError, AppResult, Call, CallStatus, PageResult, QueryParams, SipRegister, RegisterStatus,
};
use crate::sip::SipService;

#[tauri::command]
pub async fn get_call_list(params: QueryParams) -> AppResult<PageResult<Call>> {
    // 初始化示例数据
    SipService::init_sample_data();
    
    let mut call_list = SipService::get_calls();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            call_list.retain(|call| {
                call.caller.contains(keyword) ||
                call.callee.contains(keyword) ||
                call.sip_server.contains(keyword)
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            call_list.retain(|call| {
                format!("{:?}", call.status).to_lowercase() == status.to_lowercase()
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &call_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn make_call(caller: String, callee: String, sip_server: String) -> AppResult<Call> {
    // 验证参数
    if caller.is_empty() {
        return Err(AppError::ValidationError("主叫号码不能为空".to_string()));
    }
    
    if callee.is_empty() {
        return Err(AppError::ValidationError("被叫号码不能为空".to_string()));
    }
    
    if sip_server.is_empty() {
        return Err(AppError::ValidationError("SIP服务器不能为空".to_string()));
    }
    
    // 创建通话
    SipService::create_call(caller, callee, sip_server)
}

#[tauri::command]
pub async fn hangup_call(call_id: String) -> AppResult<()> {
    SipService::hangup_call(&call_id)
}

#[tauri::command]
pub async fn get_call_detail(call_id: String) -> AppResult<Call> {
    SipService::get_call_detail(&call_id)
}

#[tauri::command]
pub async fn update_call_status(call_id: String, status: String) -> AppResult<()> {
    let call_status = match status.to_lowercase().as_str() {
        "active" => CallStatus::Active,
        "ended" => CallStatus::Ended,
        "failed" => CallStatus::Failed,
        "ringing" => CallStatus::Ringing,
        _ => return Err(AppError::ValidationError("无效的通话状态".to_string())),
    };
    
    SipService::update_call_status(&call_id, call_status)
}

#[tauri::command]
pub async fn get_register_list(params: QueryParams) -> AppResult<PageResult<SipRegister>> {
    // 初始化示例数据
    SipService::init_sample_data();
    
    let mut register_list = SipService::get_registers();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            register_list.retain(|reg| {
                reg.username.contains(keyword) ||
                reg.domain.contains(keyword) ||
                reg.sip_server.contains(keyword)
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            register_list.retain(|reg| {
                format!("{:?}", reg.status).to_lowercase() == status.to_lowercase()
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &register_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn register_sip(
    username: String,
    domain: String,
    password: String,
    sip_server: String,
    port: u16,
) -> AppResult<SipRegister> {
    // 验证参数
    if username.is_empty() {
        return Err(AppError::ValidationError("用户名不能为空".to_string()));
    }
    
    if domain.is_empty() {
        return Err(AppError::ValidationError("域名不能为空".to_string()));
    }
    
    if password.is_empty() {
        return Err(AppError::ValidationError("密码不能为空".to_string()));
    }
    
    if sip_server.is_empty() {
        return Err(AppError::ValidationError("SIP服务器不能为空".to_string()));
    }
    
    // 创建注册记录
    let register = SipService::create_register(username, domain, password, sip_server, port)?;
    
    // 执行注册
    SipService::perform_register(&register.id)?;
    
    Ok(register)
}

#[tauri::command]
pub async fn unregister_sip(register_id: String) -> AppResult<()> {
    SipService::unregister_sip(&register_id)
}

#[tauri::command]
pub async fn update_register_heartbeat(register_id: String) -> AppResult<()> {
    SipService::update_heartbeat(&register_id)
}

#[tauri::command]
pub async fn test_sip_connection(sip_server: String, port: u16) -> AppResult<bool> {
    SipService::test_sip_server_connection(&sip_server, port)
}

#[tauri::command]
pub async fn get_call_statistics() -> AppResult<std::collections::HashMap<String, i64>> {
    Ok(SipService::get_call_statistics())
}

#[tauri::command]
pub async fn get_active_calls_count() -> AppResult<i64> {
    Ok(SipService::get_active_calls_count())
}

#[tauri::command]
pub async fn get_registered_users_count() -> AppResult<i64> {
    Ok(SipService::get_registered_users_count())
}

#[tauri::command]
pub async fn check_expired_registrations() -> AppResult<Vec<String>> {
    Ok(SipService::check_expired_registrations())
}

#[tauri::command]
pub async fn export_calls() -> AppResult<Vec<Call>> {
    Ok(SipService::get_calls())
}

#[tauri::command]
pub async fn export_registers() -> AppResult<Vec<SipRegister>> {
    Ok(SipService::get_registers())
}
